"""Prometheus metrics helpers."""
from contextlib import contextmanager
import time

import prometheus_client

from cki_lib import misc


class LoadIndex:
    """Turn prometheus metric into a load index measurement."""

    def __init__(self, name, description):
        """Initialize."""
        self.metric = prometheus_client.Summary(name, description)
        self.enter_ts = None
        self.last_exit_ts = None

    def enter(self):
        """Store enter timestamp."""
        self.enter_ts = time.monotonic()

    def exit(self):
        """Store exit timestamp and update metric."""
        exit_ts = time.monotonic()

        try:
            load = (exit_ts - self.enter_ts) / (exit_ts - self.last_exit_ts)
        except TypeError:
            # last_exit_ts is not yet defined on the first call.
            pass
        else:
            self.metric.observe(load)

        self.last_exit_ts = exit_ts

    @contextmanager
    def context(self):
        """Measure load index as a context manager."""
        self.enter()
        try:
            yield
        finally:
            self.exit()


def prometheus_init(prometheus=None):
    # pylint: disable=unused-argument
    """Initialize prometheus server."""
    enabled = misc.get_env_bool('CKI_METRICS_ENABLED', False)
    port = misc.get_env_int('CKI_METRICS_PORT', 8000)

    if enabled:
        prometheus_client.disable_created_metrics()
        prometheus_client.start_http_server(port)
